package option

import (
	"context"
	"strings"

	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/product/rpc/productclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateAttributeOptionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateAttributeOptionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateAttributeOptionLogic {
	return &UpdateAttributeOptionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateAttributeOptionLogic) UpdateAttributeOption(req *types.UpdateAttributeOptionReq) (resp *types.BaseMsgResp, err error) {
	if len(req.Ids) > 0 {
		res, err := l.svcCtx.ProductRpc.UpdateAttributeOption(l.ctx, &productclient.AttributeOptionInfo{
			Status: req.Status,
			Ids:    req.Ids,
		})
		if err != nil {
			return nil, err
		}

		return &types.BaseMsgResp{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
		}, nil
	}

	if req.Id == nil || *req.Id == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	if req.Name != nil && len(strings.TrimSpace(*req.Name)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "attribute.optionNameRequired"))
	}

	adminId := jwt.GetBackendUserId(l.ctx)

	res, err := l.svcCtx.ProductRpc.UpdateAttributeOption(l.ctx, &productclient.AttributeOptionInfo{
		Id:        req.Id,
		Name:      req.Name,
		Slug:      req.Slug,
		Sort:      req.Sort,
		Status:    req.Status,
		UpdatedBy: pointy.GetPointer(adminId),
	})
	if err != nil {
		return nil, err
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
